package com.dily.study.user.filter;

import com.alibaba.fastjson.JSONObject;
import com.dily.study.user.entity.dto.LoginUser;
import com.dily.study.user.service.UserService;
import com.dily.study.user.utils.StringRedisUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Date: 2022-06-10 星期五
 * Time: 16:36
 * Author: Dily_Su
 * Remark:
 */

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisUtils redisUtils;
    @Autowired
    private UserService userService;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取 token
        String token = request.getHeader("token");

        // 无 token 放行，这里其实是去登录
        if (StringUtils.isEmpty(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 解析 token
        LoginUser tokenUser;
        try {
            tokenUser = userService.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token 非法");
        }

        // 从 redis 获取 user
        String redisKey = "login:" + tokenUser.getUser().getUsername() + "(" + tokenUser.getUser().getId() + ")";
        String json = redisUtils.get(redisKey);
        LoginUser loginUser = JSONObject.parseObject(json, LoginUser.class);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        // 第一个 user, 第三个权限，获取权限信息，封装到 Authentication
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 已认证用户存入线程本地
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
